package com.kylin.common.datascope.service;

import com.kylin.common.redis.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * 数据权限服务
 *
 * @author wuhao
 * @version 1.0 - 2019-08-19
 */
@Service
@Slf4j
public class DataScopeService
{
    /** redis可以需要和la-system中保持一致 */
    private static final String ROLE_LIST_KEY = "sys:role:list";
    private static final long EXPIRE_TIME = 24 * 60 * 60 ;

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private RedisService redisService;
    

    /**
     * 根据角色的key获取角色对象
     * @param roleKey 角色key
     * @return  
     * @author wuhao
     * @version 1.0.0 - 2023/4/8
     */
    public Role getRoleByKey(String roleKey) {
        List<Role> roleList =redisService.getCacheList(ROLE_LIST_KEY);
        if(ObjectUtils.isEmpty(roleList)) {
            roleList = jdbcTemplate.query(
                    "select id, role_name, role_key, data_scope from sys_role where status = '0' and delete_flag = 1",
                    rowMapper);
            redisService.setCacheList(ROLE_LIST_KEY, roleList);
            redisService.expire(ROLE_LIST_KEY, EXPIRE_TIME);
        }
        if(ObjectUtils.isNotEmpty(roleList)) {
            return roleList.stream().filter(c -> roleKey.equals(c.getRoleKey())).findFirst().orElse(null);
        }
        return null;
    }

    @SuppressWarnings("unused")
    private BeanPropertyRowMapper<Role> rowMapper = new BeanPropertyRowMapper<Role>(Role.class){
        @Override
        protected void initBeanWrapper(BeanWrapper bw) {
            super.initBeanWrapper(bw);
        }
    };

//    @Autowired
//    private RemoteUserService remoteUserService;
//
//    /**
//     * 查询当前用户信息
//     *
//     * @return 用户基本信息
//     */
//    public UserInfo info()
//    {
//        String username = SecurityUtils.getUsername();
//        ResultBean<UserInfo> userResult = remoteUserService.getUserInfo(username);
//        if (ObjectUtils.isEmpty(userResult) || ObjectUtils.isEmpty(userResult.getData()))
//        {
//            log.info("数据权限范围查询用户：{} 不存在.", username);
//            return null;
//        }
//        return userResult.getData();
//    }
}
